#!/usr/bin/python
# ~*~ coding: utf-8 ~*~

import sys
import json
import os
import importlib
importlib.reload(sys)
from mysqldb import DbSearch
from DingDing import SendMs
import datetime
import time
from tasks import *
from SelfHealing import SelfHealing
from mailers import SendMessages
from alert_template import AlertTemplate
import redis

#数据库
#获取redis配置
from confs.Configs import *

#alert 队列
redisPool = redis.ConnectionPool(host=redis_host,port=redis_port,db=redis_db,password=redis_password)
client = redis.Redis(connection_pool=redisPool)
#连接redis
rc = redis.Redis(host=redis_host, port=redis_port,db=redis_db,password=redis_password)

content = '如果队列中暂无元素,将休息3秒钟~~~'
logger.info(content)
flag = 'icbc'
while True:
	num = client.llen(flag)
	if num == 0:
		#print ('sleep 3s')
		time.sleep(3)
	else:
		comment = '队列中元素个数是%s,开始消费~~~'%(str(num))
		logger.info(comment)
		task = client.brpop('icbc',1)
		msg = task[1]
		#转换json
		msg = json.loads(msg)
		logger.info('消费者端获取到的元素是{}'.format(msg))

		#json格式处理

		for t in AlertTemplate:
			exec("{} = '{}'".format(AlertTemplate[t], msg[t]))

		#IP
		rc.hsetnx(alarm,'IP', ip)

		if status == 'OK':
			last_status = ''
			if rc.hexists(alarm, alertpj):
				alert = rc.hget(alarm, alertpj)
				alert_loads = json.loads(alert)
				alertime = alert_loads['alertime']
				last_status = alert_loads['status'] if 'status' in alert_loads else ''

			alert_dumps = json.dumps({"alertime":0,"fixtime":0,"status":status})
			rc.hset(alarm,alertpj,alert_dumps)

			#告警信息记录
			if last_status and last_status != status:
				alertmsg = 'IP:%s, 告警项目: %s,自愈项: %s, 告警状态: %s,上次告警状态: %s,告警%d次后恢复' % (ip, alarm, alertpj, status, last_status,alertime)
			else:
				alertmsg = 'IP:%s, 告警项目: %s,自愈项: %s, 告警状态: %s,上次告警状态: %s'%(ip,alarm,alertpj,status,last_status)
			logger.info(alertmsg)

		else:

			#通过报警项目报警次数去做处理
			if rc.hexists(alarm,alertpj):
				alert = rc.hget(alarm,alertpj)
				alert = json.loads(alert)
				alertime = alert['alertime']
				fixtime = int(alert['fixtime'])
				last_status = alert['status']

				alertime = int(alertime) + 1
				alert['alertime']=alertime
				alert['status'] = status

				##判断告警次数处理逻辑
				if alertpj in SelfHealing:
					switchtime = SelfHealing[alertpj]['time']
					switchcmd = SelfHealing[alertpj]['cmd']
					maxfixtime = SelfHealing[alertpj]['fixtime']
				else:
					continue

				if alertime >= switchtime:

					if fixtime < maxfixtime:

						db = DbSearch()
						switch_status = db.AutoStatus(alertpj)
						auto_status = db.McStatus(alarm)
						if switch_status and auto_status:

							# 发送告警
							try:
								alert_type, alert_type_link = db.SendAlert(alarm)
								user = db.SendUser()
								MSG = {'alert_type':alert_type,'alert_type_link':alert_type_link,'user':user}

								#获取资产信息
								db = DbSearch()
								asset = db.Asset(ip)
								RemoteDispatch.delay(asset,switchcmd,MSG)

								#告警信息记录
								selfhealingmes = 'IP:%s, 告警项目: %s,自愈项: %s, 告警状态: %s, 告警次数: %s,自愈次数: %s 小于等于最大设定值 %s,本次执行动作%s, 将继续尝试修复'%(ip,alarm,alertpj,status,alertime,fixtime,maxfixtime,switchcmd)
								logger.info(selfhealingmes)

								# 次数加1
								fixtime += 1
								alert['fixtime'] = fixtime
								rc.hset(alarm, alertpj, json.dumps(alert))

							except Exception as e:
								logger.info(e)


						else:
							# 告警信息记录
							selfhealingmes = 'IP:%s, 告警项目: %s,自愈项: %s, 自愈状态: %s 禁止触发自愈动作,跳过！！！' % (
							ip, alarm, alertpj, str(auto_status))
							logger.info(selfhealingmes)

					else:
						selfhealingmes = 'IP:%s, 告警项目: %s,自愈项: %s, 告警状态: %s, 告警次数: %s,自愈次数: %s 大于设定值 %s 不做处理'%(ip,alarm,alertpj,status,alertime,fixtime,maxfixtime)
						logger.info(selfhealingmes)
						fixtime += 1
						alert['fixtime']= fixtime
						rc.hset(alarm,alertpj,json.dumps(alert))

				else:
					rc.hset(alarm,alertpj,json.dumps(alert))
					#告警信息记录
					alertmsg = '本次告警信息是 IP:%s, 告警项目: %s,自愈项: %s, 告警状态: %s, 告警次数: %s'%(ip,alarm,alertpj,status,alertime)
					logger.info(alertmsg)

			else:
				alertime = 1
				fixtime = 0
				status = 'BAD'
				alert = json.dumps({"alertime":alertime,"fixtime":fixtime,"status":status})
				rc.hset(alarm,alertpj,alert)

				#告警信息记录
				alertmsg = '首次创建告警信息是 IP:%s, 告警项目: %s,自愈项: %s, 告警状态: %s, 告警次数: %s'%(ip,alarm,alertpj,status,alertime)
				logger.info(alertmsg)